package com.yunjian.admin.config.shiro;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonpPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
	
	private static final Logger logger = LoggerFactory.getLogger(JsonpPermissionsAuthorizationFilter.class);
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

        Subject subject = getSubject(request, response);
        // If the subject isn't identified, redirect to login URL
        if (subject.getPrincipal() == null) {
        	// 替换为内部跳转
            try {
				WebUtils.toHttp(request).getRequestDispatcher(getLoginUrl()).forward(request, response);
			} catch (ServletException e) {
				logger.error("错误", e);
			}
        } else {
            // If subject is known but not authorized, redirect to the unauthorized URL if there is one
            // If no unauthorized URL is specified, just return an unauthorized HTTP status code
            String unauthorizedUrl = getUnauthorizedUrl();
            //SHIRO-142 - ensure that redirect _or_ error code occurs - both cannot happen due to response commit:
            if (StringUtils.hasText(unauthorizedUrl)) {
            	try {
    				WebUtils.toHttp(request).getRequestDispatcher(unauthorizedUrl).forward(request, response);
    			} catch (ServletException e) {
    				logger.error("错误", e);
    			}
            } else {
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }
        return false;
    }
	
	
}
